local cjson = require('cjson')
local client = require "resty.kafka.client"
local producer = require "resty.kafka.producer"
local bigdatatool = require("resty.bigdatatool")
local uaparse = require("resty.uaparse")

local args = ngx.req.get_uri_args()
ngx.req.read_body()
local pargs = ngx.req.get_post_args()
--local data = pargs.data
--local ext = pargs.ext
local data = pargs.data or args.data
local ext = pargs.ext or args.ext

local project = args.project

--校验项目名称
if not bigdatatool.isMatch(project or '','^(production|default)$') then
    return
end

local broker_list = {
    {
        host = "192.168.0.1",
        port = 9092
    },{
        host = "192.168.0.1",
        port = 9092
    }
}
--解决消息没有产生时间问题
producer.zsapi_version = 2
local bp = producer:new(broker_list, { api_version = 2})
--数据校验不通过停止往下执行
if ext == nil or ext ~= 'crc='..bigdatatool.hashCode(data) then
    --收集未通过crc验证数据信息
    bp:send('not_match_sa',nil, cjson.encode({ext = ext,data=data,src='sa.gif'}))
    return
end

local decodest = pcall(function()
    data = ngx.decode_base64(data)
    --lua int64 处理
    local pattern = [[("[$\-\w]+":)(\d{15,})]]
    local replacement = [[$1"$2"]]
    local new_json, err = ngx.re.gsub(data, pattern, replacement)
    data = new_json
    data = cjson.decode(data)
end)

if not decodest then
    return
end

local ip = bigdatatool.getip()
local addr = {}
xpcall(function()
    --解析ip所在地区
    local res,err = bigdatatool.ipfind(ip)
    if err then
        ngx.log(ngx.ERR,err)
    else
        addr = {province=res.region_name,city=res.city_name,country=res.country_name,isp_domain=res.isp_domain}
    end
end,function(err)
    ngx.log(ngx.ERR,tostring(err))
end)
data.project = project
data.recv_time = ngx.time()
data.ua = ngx.var.http_user_agent
local uap = {}
pcall(function ()
    --浏览器解析出的信息
    uap = uaparse.parse(data.ua)
end)
data.uap = uap
data.addr = addr
data.ip = ip
bigdatatool.verifytime(data)
pcall(function()
    if data.properties['$os'] == nil then
        data.properties['$os'] = uap.os
    end
    if data.properties['$os_version'] == nil then
        data.properties['$os_version'] = uap.os_version
    end
    if data.properties['$country'] == nil then
        data.properties['$country'] = addr.country
    end
    if data.properties['$province'] == nil then
        data.properties['$province'] = addr.province
    end
    if data.properties['$city'] == nil then
        data.properties['$city'] = addr.city
    end
    if data.properties.platform_type == nil and (data.properties['$lib'] == 'Android' or uap.os == 'Android') then
        data.properties.platform_type = 'Android'
    end
end)
local topic = 'bigdata_event'
if bigdatatool.isMatch(data.type,'^profile_') then
    topic = 'bigdata_user'
elseif bigdatatool.isMatch(data.type,'^item_') then
    topic = 'bigdata_item'
end
local ok, err = bp:send(topic,nil, cjson.encode(data))
if not ok then
    ngx.log(ngx.ERR,err)
end
